package com.mooer.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.mooer.MooerApplication;
import com.mooer.R;
import com.mooer.bean.SearchLocation;
import com.mooer.bean.SignInfo;
import com.mooer.exception.SVException;
import com.mooer.http.HttpUtils;
import com.mooer.utils.ui.BitmapViewBinder;
import com.mooer.utils.ui.ProgressLinearLayout;

public class SignNear extends Activity implements OnClickListener {

	private ListView listView;

	private ProgressLinearLayout footer;

	private SimpleAdapter adapter;

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

	private long taskId;

	private MooerApplication mooerApp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sign_near);
		mooerApp = (MooerApplication) getApplication();
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		adapter = new SimpleAdapter(
				this,
				list,
				R.layout.sign_near_item,
				new String[] { "name", "businessName", "date", "icon" },
				new int[] { R.id.name, R.id.business_name, R.id.date, R.id.icon });
		adapter.setViewBinder(new BitmapViewBinder());
		listView.setAdapter(adapter);
		footer.setOnClickListener(this);

		SearchLocation location = new SearchLocation();
		location.setLatitude(32.05724);
		location.setLongitude(118.740275);
		location.setRadius(20000);
		new SignNearTask().execute(location);
	}

	private class SignNearTask extends
			AsyncTask<SearchLocation, Integer, List<SignInfo>> {

		private boolean isException;

		@Override
		protected List<SignInfo> doInBackground(SearchLocation... params) {
			List<SignInfo> list = null;
			try {
				list = HttpUtils.fetchNearSignedInfoList(params[0], 0, 100);
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<SignInfo> result) {
			super.onPostExecute(result);
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					for (SignInfo signInfo : result) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("name",
								getString(R.string.sign_user_tip, signInfo
										.getUser().getUserName() + "  "));
						map.put("businessName",
								getString(R.string.sign_tip, signInfo.getShop()
										.getName()));
						map.put("date", signInfo.getDate());
						map.put("userId", signInfo.getUser().getId());
						map.put("picPath", signInfo.getUser().getPhoto());
						map.put("icon", mooerApp.getAvatarIcon());
						list.add(map);
					}
					listView.removeFooterView(footer);
					adapter.notifyDataSetChanged();
					new BitmapTask().execute("");
				} else {
					footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
							View.GONE);
					footer.setText(null, "附近暂无签到信息");
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	public class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<Map<String, Object>> cacheList = new ArrayList<Map<String, Object>>();
			cacheList.addAll(list);
			Iterator<Map<String, Object>> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId) {
					break;
				}
				Map<String, Object> map = it.next();
				Bitmap icon = null;
				try {
					if (map.get("icon") == mooerApp.getAvatarIcon()) {
						icon = HttpUtils.downloadBitmap(
								(Integer) map.get("userId") + "",
								(String) map.get("picPath"));
						map.put("icon", icon);
						publishProgress(0);
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			adapter.notifyDataSetChanged();
		}

	}

}
